package com.ruge.test.springMVC.shiro.realm.session;

import com.ruge.test.Redis.jedis.JedisUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.SerializationUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 爱丽丝、如歌  创建于 2018/7/6 19:38
 * 说明:  TODO
 */
public class RedisSessionDao extends AbstractSessionDAO {
    @Autowired
    private JedisUtil jedisUtil;

    private final String SHIRO_SESSION_PREFIX = "ruge-session";

    private byte[] getKey(String key) {
        return (SHIRO_SESSION_PREFIX + key).getBytes();
    }

    private void insertSession(Session session) {
        if (session != null && session.getId() != null) {
            byte[] key = getKey(session.getId().toString());
            byte[] serialize = SerializationUtils.serialize(session);
            jedisUtil.set(key, serialize);
            jedisUtil.expire(key, 600);
        }
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable serializable = generateSessionId(session);
        insertSession(session);
        return serializable;
    }

    @Override
    protected Session doReadSession(Serializable serializable) {
        if (serializable == null) {
            return null;
        }
        byte[] key = getKey(serializable.toString());
        byte[] bytes = jedisUtil.getKey(key);
        Session deserialize = (Session) SerializationUtils.deserialize(bytes);
        return deserialize;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        insertSession(session);
    }

    @Override
    public void delete(Session session) {
        if (session == null || session.getId() == null) {

        }
        byte[] key = getKey(session.getId().toString());
        jedisUtil.delete(key);
    }

    /**
     * 获得指定的存活的session
     *
     * @return
     */
    @Override
    public Collection<Session> getActiveSessions() {
        Set<byte[]> keys = jedisUtil.keys(SHIRO_SESSION_PREFIX);
        Set<Session> sessions = new HashSet<>();
        if (CollectionUtils.isEmpty(sessions)) {
            return sessions;
        }
        for (byte[] k : keys
                ) {
            Session session = (Session) SerializationUtils.deserialize(jedisUtil.getKey(k));
            sessions.add(session);
        }
        return sessions;
    }
}
